<template>
  <div class="table-body-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
        <el-input
          v-model="state.tableData.param.nodeName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
          class="search-input"
        />
        <el-select v-model="state.tableData.param.flowStatus" placeholder="请选择流程状态" clearable class="ml10 search-input">
          <el-option
            v-for="dict in flow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-date-picker
          clearable
          v-model="state.tableData.param.createDate"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          class="ml10 search-input"
          placeholder="选择创建时间">
        </el-date-picker>
        <el-button type="primary" @click="handleQuery" class="ml10"><el-icon>
						<ele-Search />
					</el-icon>搜索</el-button>
        <el-button @click="resetQuery"><el-icon>
						<ele-Refresh />
					</el-icon>重置</el-button>
    </div>
    <el-table v-loading="state.tableData.loading" :data="state.tableData.data" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true"/>
      <el-table-column label="任务名称" width="200" align="center" prop="nodeName" :show-overflow-tooltip="true"/>
      <el-table-column label="审批人" align="center" prop="approver" :show-overflow-tooltip="true"/>
      <el-table-column label="转办人" align="center" prop="transferredBy" :show-overflow-tooltip="true"/>
      <el-table-column label="委派人" align="center" prop="delegate" :show-overflow-tooltip="true"/>
      <el-table-column label="流程状态" align="center" prop="flowStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="flow_status" :value="scope.row.flowStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="激活状态" align="center" prop="activityStatus" width="140" sortable="custom" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="activity_status" :value="scope.row.activityStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <txt-link 
            text="办理"
            @click="handle(scope.row, false)"
            v-auth="'flow:execute:handle'"
          />
          <txt-link
            @click="handle(scope.row, true)"
            v-auth="'flow:execute:handle'"
            text="任意跳转"
          />
          <txt-link
            text="转办"
            @click="transferShow(scope.row, '转办')"
            v-auth="'flow:execute:handle'"
          />
          <txt-link
            text="加签"
            @click="transferShow(scope.row, '加签')"
            v-auth="'flow:execute:handle'"
          />
          <txt-link
            text="委派"
            @click="transferShow(scope.row, '委派')"
            v-auth="'flow:execute:handle'"
          />
          <txt-link
            text="减签"
            @click="transferShow(scope.row, '减签')"
            v-auth="'flow:execute:handle'"
          />
          <txt-link
            text="激活"
            v-if="scope.row.activityStatus === 0"
            @click="toActive(scope.row.instanceId)"
          />
          <txt-link
            text="挂起"
            v-if="scope.row.activityStatus === 1"
            @click="toUnActive(scope.row.instanceId)"
          />
          <txt-link
            text="流程图"
            @click="toFlowImage(scope.row.instanceId)"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
                v-show="state.tableData.total>0"
                :total="state.tableData.total"
                v-model:page="state.tableData.param.current"
                v-model:limit="state.tableData.param.size"
                @pagination="getList"
            />
    </el-card>

    <component ref="componentRef" :is="approve" v-model="businessId" :type="'0'" :taskId="taskId" :showAnyNode="showAnyNode" :formId="formPath" @refresh="getList"></component>
    <el-dialog title="流程图" v-model="flowChart" width="1100">
      <img :src="imgUrl" width="1000" height="500" style="margin:0 auto"/>
    </el-dialog>

    <!-- 权限标识：选择用户 -->
    <el-dialog :title="`${dialogTitle}用户选择`" v-if="userVisible" v-model="userVisible" width="80%" append-to-body>
      <selectUser :postParams="state.postParams" :type="dialogTitle" v-model:selectUser="state.formData.assigneePermission" v-model:userVisible="userVisible" @handleUserSelect="handleUserSelect"></selectUser>
    </el-dialog>
    <el-dialog title="流程图" width="70%" v-model="state.flowChart" append-to-body>
        <WarmChart :insId="state.insId"></WarmChart>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Todo">
import * as api from "/@/api/flow/execute";
import { active, unActive } from "/@/api/flow/execute";
import selectUser from "/@/views/components/selectUser.vue";
import constConfig from '/@/utils/constConfig';

const WarmChart = defineAsyncComponent(() => import('/@/views/flow/definition/warm_chart.vue'));
const { proxy } = <any>getCurrentInstance();
const { flow_status, activity_status } = proxy.useDict('flow_status', 'activity_status');
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const imgUrl = ref("");
const flowChart = ref(false);
const approve = ref();
const taskId = ref("");
const businessId = ref("");
const formPath = ref("");
const dialogTitle = ref("");
const userVisible = ref(false);
const showAnyNode = ref(false);
const componentRef = ref();

const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			nodeName: null,
      flowStatus: null,
      approver: null,
      createDate: null,
			...constConfig.pageModel,
		},
	},
	formData: {
		assigneePermission: [],
	},
  insId: '',
  flowChart: false,
  postParams: {
    taskId: null,
    operatorType: null},
	...constConfig.dialogType
});

onActivated(() => {
  getList();
});

function getList() {
  state.tableData.loading = true;
  api.toDoPage(state.tableData.param).then(res => {
    state.tableData.data = res.data.records??[];
		state.tableData.total = res.data.total;
		state.tableData.loading = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection:any) {
  ids.value = selection.map((item:any) => item.id)
  single.value = selection.length!==1
  multiple.value = !selection.length
}
/** 办理按钮操作 */
async function handle(row:any, _showAnyNode:boolean) {
  approve.value = null;
  taskId.value = row.id;
  businessId.value = row.businessId;
  showAnyNode.value = _showAnyNode;
  if (!row.formPath) {
    row.formPath = '/@/views/biz/flow/leave/dialog.vue';
  }
  if (row.formCustom == 'N') {
    // 实际情况是，不同条件对应不同的页面，所以用动态导入组件
     const page = await import(/* @vite-ignore */`/@/views/${row.formPath}`);
     approve.value = page.default;
  } else if (row.formCustom === "Y") {
    formPath.value = row.formPath;
    const page = await import(/* @vite-ignore */`/@/views/form/definition/formDialog.vue`)
    approve.value = page.default;
  }
  nextTick(() => {
    componentRef.value.openDialog(showAnyNode.value?'20':'30', businessId.value)
  })
}
const toFlowImage = (instanceId:string) => {
      state.insId = instanceId;
      state.flowChart = true
    }

/** 转办|加签|委派|减签弹框显示按钮操作 */
function transferShow(row:any, title:string) {
  state.formData.assigneePermission = [];
  taskId.value = row.id;
  dialogTitle.value = title;
  api.getTaskById(taskId.value).then(res => {
    state.formData.assigneePermission = res.data.assigneePermission ? res.data.assigneePermission.split(",") : [];
  });
  userVisible.value = true;
  let operatorTypeObj:any = {
    "转办": "1",
    "加签": "6",
    "委派": "3",
    "减签": "7"
  };
  state.postParams = {
    taskId: row.id,
    operatorType: operatorTypeObj[title]
  };
}

// 获取选中用户数据
function handleUserSelect(checkedItemList:any) {
  state.formData.assigneePermission = checkedItemList.map((e: any) => {
    return e.userId;
  });
  let assigneePermission = JSON.parse(JSON.stringify(state.formData.assigneePermission));
  let operatorTypeObj = {
    "转办": "2",
    "加签": "6",
    "委派": "3",
    "减签": "7"
  };
  api.interactiveType(taskId.value, Array.isArray(assigneePermission) ? assigneePermission.join(',') : assigneePermission, operatorTypeObj[dialogTitle.value]).then(() => {
    proxy.modal.msgSuccess(`${dialogTitle.value}成功`);
    open.value = false;
    getList();
  });
}

function toActive(instanceId:string) {
  proxy.modal.confirm('是否确认激活流程编号为"' + instanceId + '"的数据项？').then(function() {
    return active(instanceId);
  }).then(() => {
    getList();
    proxy.modal.msgSuccess("激活成功");
  }).catch(() => {});
}

function toUnActive(instanceId:string) {
  proxy.modal.confirm('是否确认挂起流程编号为"' + instanceId + '"的数据项？').then(function() {
    return unActive(instanceId);
  }).then(() => {
    getList();
    proxy.modal.msgSuccess("挂起成功");
  }).catch(() => {});
}
// 页面加载时
onMounted(() => {
	getList();
});
</script>
<style scoped lang="scss">
.table-body-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>